﻿using System;
using System.Collections.Generic;

namespace ETHotfix
{
    public class TreeManager
    {
        static TreeManager inst;
        Dictionary<Type, INodeHandle> handleDict = new Dictionary<Type, INodeHandle>();

        public static TreeManager Inst
        {
            get
            {
                return inst??(new TreeManager(typeof(TreeManager).Assembly.GetTypes()));
            }
        }

        TreeManager(Type[] ts)
        {
            var interfaceType = typeof(INodeHandle);
            foreach (var type in ts)
            {
                if (type.IsAbstract || type.IsInterface)
                    continue;
                if (!interfaceType.IsAssignableFrom(type))
                    continue;
                object[] attrs = type.GetCustomAttributes(typeof(NodeEventAttribute), false);
                if (attrs.Length == 0)
                    continue;
                var attr = attrs[0] as NodeEventAttribute;

                var obj = Activator.CreateInstance(type) as INodeHandle;
                handleDict.Add(attr.type, obj);
            }
        }

        public void Execute(Unit unit)
        {
            var com = unit.GetComponent<TreeComponent>();
            if (com == null)
                return;

            INodeHandle nodeHandle;
            com.runtimeTree.ForEach(runtimeNode => 
            {
                handleDict.TryGetValue(runtimeNode.node.GetType(), out nodeHandle);
                nodeHandle?.Handle(com.runtimeTree, runtimeNode, unit);
            });
        }
    }
}
